/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: JwtTokenUtil
 * Author:   zhouheng
 * Date:     2019/4/16 8:00
 * Description: token 生成器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.dubbo.user.provider.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;

/**
 * 〈一句话功能简述〉<br> 
 * 〈token 生成器〉
 *
 * @author zhouheng
 * @create 2019/4/16
 * @since 1.0.0
 */
public class JwtTokenUtil {

    private static Key getKeyInstance(){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] dc = DatatypeConverter.parseBase64Binary("star-user");
        return new SecretKeySpec(dc,signatureAlgorithm.getJcaName());
    }

    /**
     * @description: 生成token的方法
     * @date: 2019/4/16 8:04
     * @author:zhouheng
     */
    public static String generatorToken(JwtInfo jwtInfo, int expire) {
        return Jwts.builder().setExpiration(DateTime.now().plusSeconds(expire).toDate())
                .signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .claim(JwtConstants.JWT_KEY_USER_ID,jwtInfo.getUid())
                .compact();
    }

    /**
     * @description: 解析token
     * @date: 2019/4/16 23:40
     * @author:zhouheng
     */
    public static JwtInfo parseTokenInfo(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();

        return new JwtInfo(claims.get(JwtConstants.JWT_KEY_USER_ID).toString());
    }
}